package com.jdls.web;

import com.jdls.pojo.User;
import com.jdls.service.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author 嘉德罗斯
 * @date 2021/9/4
 */
@WebServlet("/RegisterServlet")
public class RegisterServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8"); // 处理请求参数的乱码
        response.setContentType("text/html;charset=utf-8"); // 处理响应数据的乱码
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        UserService userService = new UserService();
        User user1 = userService.register(username);
        String checkCode = request.getParameter("checkCode");

        // 程序生成的验证码，从Session获取
        HttpSession session = request.getSession();
        String checkCodeGen = (String) session.getAttribute("checkCodeGen");

        // 比对
        if(!checkCodeGen.equalsIgnoreCase(checkCode)){

            request.setAttribute("register_msg","验证码错误");
            request.getRequestDispatcher("/register.jsp").forward(request,response);

            // 不允许注册
            return;
        }
        if (user1==null){
            User user = new User();
            user.setUsername(username);
            user.setPassword(password);
            userService.add(user);
            request.setAttribute("reg","创建成功，请登录");
            response.sendRedirect("/user/Login.jsp");
        }else {
            request.setAttribute("register","用户名已存在");
            request.getRequestDispatcher("/register.jsp").forward(request,response);
        }
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
